<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成绩管理</title>
    <link rel="stylesheet" href="/public/lib/element-ui/index.css">
    <script src="/public/lib/vue.js"></script>
    <script src="/public/lib/element-ui/index.js"></script>
    <script src="/public/lib/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            background-color: #f5f5f5;
        }
        .management-container {
            padding: 20px;
        }
        .management-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .search-box {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }
        .search-input {
            width: 200px;
        }
        .table-container {
            background-color: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .pagination-container {
            margin-top: 20px;
            text-align: right;
        }
        .upload-demo {
            margin-left: 10px;
        }
        .import-template {
            margin-left: 10px;
            font-size: 12px;
            color: #409EFF;
            cursor: pointer;
        }
        .import-template:hover {
            text-decoration: underline;
        }
        .batch-actions {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="management-container">
        <div class="management-header">
            <h3>成绩管理</h3>
            <div>
                <el-button type="primary" @click="showAddDialog = true">+ 新增</el-button>
            </div>
        </div>

        <!-- 搜索栏 -->
        <div class="search-box">
            <el-input
                    v-model="searchForm.student_name"
                    placeholder="请输入姓名"
                    class="search-input"
                    clearable>
            </el-input>
            <el-input
                    v-model="searchForm.course_name"
                    placeholder="请输入课程名称"
                    class="search-input"
                    clearable>
            </el-input>
            <el-button type="primary" @click="getScores">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>

            <!-- 批量导入 -->
            <el-upload
                    class="upload-demo"
                    action="/api/scores/import"
                    :headers="uploadHeaders"
                    :on-success="handleImportSuccess"
                    :on-error="handleImportError"
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    accept=".xlsx,.xls,.csv">
                <el-button type="success">导入</el-button>
            </el-upload>

            <span class="import-template" @click="downloadTemplate">下载导入模板</span>
        </div>

        <!-- 批量操作 -->
        <div class="batch-actions" v-if="selectedScores.length > 0">
            <el-button type="danger" @click="batchDelete" size="small">批量删除 ({{ selectedScores.length }})</el-button>
        </div>

        <!-- 成绩表格 -->
        <div class="table-container">
            <el-table
                    :data="scores"
                    border
                    style="width: 100%"
                    @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="id" label="ID" width="80"></el-table-column>
                <el-table-column prop="student_id" label="学号"></el-table-column>
                <el-table-column prop="student_name" label="姓名"></el-table-column>
                <el-table-column prop="course_name" label="课程名称"></el-table-column>
                <el-table-column prop="score" label="分数">
                    <template slot-scope="scope">
                            <span :class="{'high-score': scope.row.score >= 90, 'low-score': scope.row.score < 60}">
                                {{ scope.row.score }}
                            </span>
                    </template>
                </el-table-column>
                <el-table-column prop="semester" label="学期"></el-table-column>
                <el-table-column prop="create_time" label="创建时间"></el-table-column>
                <el-table-column prop="update_time" label="最后修改时间"></el-table-column>
                <el-table-column label="操作" width="150">
                    <template slot-scope="scope">
                        <el-button type="text" @click="editScore(scope.row)">编辑</el-button>
                        <el-button type="text" style="color: #F56C6C;" @click="deleteScore(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
    </div>

    <!-- 新增/编辑成绩对话框 -->
    <el-dialog :title="isEditing ? '编辑成绩' : '新增成绩'" :visible.sync="showAddDialog" width="500px">
        <el-form :model="scoreForm" :rules="rules" ref="scoreForm" label-width="80px">
            <el-form-item label="学号" prop="student_id">
                <el-input v-model="scoreForm.student_id" placeholder="请输入学号"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="student_name">
                <el-input v-model="scoreForm.student_name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="课程" prop="course_name">
                <el-input v-model="scoreForm.course_name" placeholder="请输入课程名称"></el-input>
            </el-form-item>
            <el-form-item label="分数" prop="score">
                <el-input v-model="scoreForm.score" placeholder="请输入分数" type="number" min="0" max="100">
                    <template slot="append">分</template>
                </el-input>
            </el-form-item>
            <el-form-item label="学期" prop="semester">
                <el-select v-model="scoreForm.semester" placeholder="请选择学期" style="width: 100%;">
                    <el-option label="2024-2025学年第一学期" value="2024-2025学年第一学期"></el-option>
                    <el-option label="2024-2025学年第二学期" value="2024-2025学年第二学期"></el-option>
                    <el-option label="2025-2026学年第一学期" value="2025-2026学年第一学期"></el-option>
                    <el-option label="2025-2026学年第二学期" value="2025-2026学年第二学期"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAddDialog = false">取消</el-button>
            <el-button type="primary" @click="saveScore">{{ isEditing ? '更新' : '确定' }}</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                scores: [],
                selectedScores: [],
                searchForm: {
                    student_name: '',
                    course_name: ''
                },
                currentPage: 1,
                pageSize: 10,
                total: 0,
                showAddDialog: false,
                isEditing: false,
                editingScoreId: null,
                scoreForm: {
                    student_id: '',
                    student_name: '',
                    course_name: '',
                    score: '',
                    semester: ''
                },
                uploadHeaders: {
                    // 上传时自动添加session信息
                },
                rules: {
                    student_id: [
                        { required: true, message: '请输入学号', trigger: 'blur' }
                    ],
                    student_name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    course_name: [
                        { required: true, message: '请输入课程名称', trigger: 'blur' }
                    ],
                    score: [
                        { required: true, message: '请输入分数', trigger: 'blur' },
                        { type: 'number', min: 0, max: 100, message: '分数必须在0-100之间', trigger: 'blur', transform: value => Number(value) }
                    ],
                    semester: [
                        { required: true, message: '请选择学期', trigger: 'change' }
                    ]
                }
            };
        },
        mounted() {
            this.getScores();
            // 设置上传请求头
            this.uploadHeaders = {
                'X-Requested-With': 'XMLHttpRequest'
            };
        },
        methods: {
            getScores() {
                const params = {};
                if (this.searchForm.student_name) {
                    params.student_name = this.searchForm.student_name;
                }
                if (this.searchForm.course_name) {
                    params.course_name = this.searchForm.course_name;
                }

                axios.get('/api/scores', { params })
                    .then(response => {
                        if (response.data.success) {
                            this.scores = response.data.scores;
                            this.total = this.scores.length;
                        } else {
                            this.$message.error(response.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('获取成绩列表错误:', error);
                        this.$message.error('获取成绩列表失败');
                    });
            },
            resetSearch() {
                this.searchForm = {
                    student_name: '',
                    course_name: ''
                };
                this.currentPage = 1;
                this.getScores();
            },
            handleSizeChange(val) {
                this.pageSize = val;
            },
            handleCurrentChange(val) {
                this.currentPage = val;
            },
            editScore(score) {
                this.isEditing = true;
                this.editingScoreId = score.id;
                this.scoreForm = {
                    student_id: score.student_id,
                    student_name: score.student_name,
                    course_name: score.course_name,
                    score: score.score,
                    semester: score.semester
                };
                this.showAddDialog = true;
            },
            saveScore() {
                this.$refs.scoreForm.validate((valid) => {
                    if (valid) {
                        if (this.isEditing) {
                            // 更新成绩
                            axios.put(`/api/scores/${this.editingScoreId}`, this.scoreForm)
                                .then(response => {
                                    if (response.data.success) {
                                        this.$message.success('更新成绩成功');
                                        this.showAddDialog = false;
                                        this.getScores();
                                    } else {
                                        this.$message.error(response.data.message);
                                    }
                                })
                                .catch(error => {
                                    console.error('更新成绩错误:', error);
                                    this.$message.error('更新成绩失败');
                                });
                        } else {
                            // 新增成绩
                            axios.post('/api/scores', this.scoreForm)
                                .then(response => {
                                    if (response.data.success) {
                                        this.$message.success('添加成绩成功');
                                        this.showAddDialog = false;
                                        this.getScores();
                                    } else {
                                        this.$message.error(response.data.message);
                                    }
                                })
                                .catch(error => {
                                    console.error('添加成绩错误:', error);
                                    this.$message.error('添加成绩失败');
                                });
                        }
                    }
                });
            },
            deleteScore(score) {
                this.$confirm(`确定删除 "${score.student_name}" 的 "${score.course_name}" 成绩吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`/api/scores/${score.id}`)
                        .then(response => {
                            if (response.data.success) {
                                this.$message.success('删除成绩成功');
                                this.getScores();
                            } else {
                                this.$message.error(response.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('删除成绩错误:', error);
                            this.$message.error('删除成绩失败');
                        });
                });
            },
            handleSelectionChange(selection) {
                this.selectedScores = selection;
            },
            batchDelete() {
                if (this.selectedScores.length === 0) {
                    this.$message.warning('请选择要删除的成绩记录');
                    return;
                }

                const ids = this.selectedScores.map(score => score.id);
                this.$confirm(`确定删除选中的 ${ids.length} 条成绩记录吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/api/scores/batch-delete', { ids })
                        .then(response => {
                            if (response.data.success) {
                                this.$message.success('批量删除成绩成功');
                                this.selectedScores = [];
                                this.getScores();
                            } else {
                                this.$message.error(response.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('批量删除成绩错误:', error);
                            this.$message.error('批量删除成绩失败');
                        });
                });
            },
            beforeUpload(file) {
                const isExcel = file.type.includes('excel') || file.type.includes('spreadsheet');
                const isCSV = file.type === 'text/csv';
                const isLt5M = file.size / 1024 / 1024 < 5;

                if (!isExcel && !isCSV) {
                    this.$message.error('只能上传Excel或CSV文件!');
                    return false;
                }
                if (!isLt5M) {
                    this.$message.error('文件大小不能超过5MB!');
                    return false;
                }
                return true;
            },
            handleImportSuccess(response, file) {
                if (response.success) {
                    this.$message.success(response.message);
                    this.getScores();
                } else {
                    let errorMessage = response.message;
                    if (response.errors && response.errors.length > 0) {
                        errorMessage += '\n' + response.errors.slice(0, 5).join('\n');
                        if (response.errors.length > 5) {
                            errorMessage += `\n... 还有 ${response.errors.length - 5} 个错误`;
                        }
                    }
                    this.$message.error(errorMessage);
                }
            },
            handleImportError(error, file) {
                this.$message.error('文件上传失败');
                console.error('导入错误:', error);
            },
            downloadTemplate() {
                // 创建模板数据
                const templateData = [
                    {
                        student_id: '2025001',
                        student_name: '李小明',
                        course_name: '数据结构',
                        score: 85.5,
                        semester: '2024-2025学年第一学期'
                    },
                    {
                        student_id: '2025002',
                        student_name: '王小红',
                        course_name: '数据结构',
                        score: 88.0,
                        semester: '2024-2025学年第一学期'
                    }
                ];

                // 创建CSV内容
                let csvContent = 'student_id,student_name,course_name,score,semester\n';
                templateData.forEach(row => {
                    csvContent += `${row.student_id},${row.student_name},${row.course_name},${row.score},${row.semester}\n`;
                });

                // 创建下载链接
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', '成绩导入模板.csv');
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
            resetForm() {
                this.isEditing = false;
                this.editingScoreId = null;
                this.scoreForm = {
                    student_id: '',
                    student_name: '',
                    course_name: '',
                    score: '',
                    semester: ''
                };
                if (this.$refs.scoreForm) {
                    this.$refs.scoreForm.resetFields();
                }
            }
        },
        computed: {
            filteredScores() {
                let result = this.scores;

                // 分页
                this.total = result.length;
                const start = (this.currentPage - 1) * this.pageSize;
                const end = start + this.pageSize;
                return result.slice(start, end);
            }
        },
        watch: {
            showAddDialog(val) {
                if (!val) {
                    // 对话框关闭时重置表单
                    this.resetForm();
                }
            }
        }
    });
</script>
</body>
</html>